package com.web.login;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.biz.UserBizImpl;
import com.entity.UserInfo;
import com.web.listener.OnlineCountListener;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置响应的字符编码格式
		response.setContentType("text/html;charset=utf-8");
		//获得页面字符打印流out
		PrintWriter out = response.getWriter();
		
		String account=request.getParameter("account");
		String pwd=request.getParameter("pwd");
		
		UserInfo user=new UserBizImpl().login(account, pwd);
		
		if(user==null){//如果用户不存在，提示信息并返回登录界面
			//通过页面字符打印流out向页面打印提示信息
			out.print("<script>alert('账号或密码有误，请重试');history.back();</script>");
		}else{//用户存在进行进一步的操作
			//通过请求获取session对象
			HttpSession session = request.getSession();
			//将用户的登录信息放入session中
			session.setAttribute("loger", user);
			
			/*************在线人数统计****************/
			OnlineCountListener countListener=new OnlineCountListener();
			countListener.setUname(user.getUname());
			session.setAttribute("onlineCount", countListener);
			
			//设置cookie的值，记录登录过的用户名，记录时间按为1天
			Cookie c =new Cookie("logername",user.getUname());
			c.setPath("/");
			c.setMaxAge(24*60*60);
			response.addCookie(c);
			
			//根据用户是否是管理员来进行前台和后台的跳转
			if(user.getIsadmin()==0){
				//不是管理员进入前台
				response.sendRedirect("index.jsp");
			}else{
				//是管理员进入后台
				response.sendRedirect("admin/index.jsp");
			}
		}
		//刷新out
		out.flush();
		//关闭out
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
